package com.joe.demo.nio.file;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @Description 文件拷贝
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class TestFileChannelTransferTo {

    public static void main(String[] args) {
        try (FileChannel from = new FileInputStream("data.txt").getChannel();
             FileChannel to = new FileOutputStream("to.txt").getChannel()) {

            // 效率更高，底层会利用操作系统的零拷贝进行优化。
            // 数据大小 限制在 2g
            long size = from.size();
            for (long left = size; left > 0;){
                left -= from.transferTo(size - left, left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
